var {
  find,
  findOneByid,
  createOne,
  count,
  remove,
  groupBy,
} = require("../dao/base.js");
var feedbackModel = require("../models/feedback");
var administratorsModel = require("../models/admin");

//注册
module.exports.createOneFeedback = async function (req, res, next) {
  var doc = await createOne(feedbackModel, req.body);
  if (doc) {
    res.sendResult(doc, 200, "反馈成功！");
  } else {
    res.sendResult(doc, 500, "反馈失败！");
  }
};

//注册
module.exports.getFeedback = async function (req, res, next) {
  var doc = await find(feedbackModel);
  if (doc) {
    res.sendResult(doc, 200, "反馈成功！");
  } else {
    res.sendResult(doc, 500, "反馈失败！");
  }
};

module.exports.findFeedback = async function (req, res, next) {
  let params = req.body.params;
  let page = req.body.page;
  const total = await count(feedbackModel, {
    $or: [{
      name: { $regex: req.body.params.name },
      userid: { $regex: req.body.params.userid },
      title: { $regex: req.body.params.title },
      content: { $regex: req.body.params.content }
    }]
  });
  var docs = await find(feedbackModel, {
    $or: [{
      name: { $regex: req.body.params.name },
      userid: { $regex: req.body.params.userid },
      title: { $regex: req.body.params.title },
      content: { $regex: req.body.params.content }
    }]
  }, null, {
    skip: (page.pageNumber - 1) * page.pageSize,
    limit: page.pageSize,
    sort: { [page.sortColumn.column]: page.sortColumn.order },
  });
  if (docs) {
    res.sendResult(docs, 200, total);
  } else {
    res.sendResult(docs, 200, "查询失败");
  }
};

module.exports.deleteFeedback = async function (req, res, next) {
  let loginUserid = req.query.loginUserid;
  var doc = await findOneByid(administratorsModel, { userid: loginUserid });

  let needRole = '反馈管理员';
  let checkPermission = doc.permission.includes(needRole)
  ||doc.permission.includes('超级管理员')
  if(!checkPermission){
    return  res.sendResult(doc, 403, "你没有权限");
  }
  var doc = await remove(feedbackModel, { _id: req.query._id });
  if (doc) {
    res.sendResult(doc, 200, "反馈成功！");
  } else {
    res.sendResult(doc, 500, "反馈失败！");
  }
};

